package com.financing.wap.web.controller.adminapi;

import java.util.*;

import javax.servlet.http.HttpServletRequest;

import com.financing.wap.dto.DstOperationLogDTO;
import com.financing.wap.service.*;
import com.financing.wap.util.DateUtil;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.wap.common.CommonConstantUtil.CommonStatus;
import com.financing.wap.common.Pager;
import com.financing.wap.common.ResultMap;
import com.financing.wap.dto.DstArticleDTO;
import com.financing.wap.dto.DstNewrankArticleDTO;
import com.financing.wap.dto.DstUserArticleDTO;
import com.financing.wap.service.weixin.service.WeixinService;
import com.financing.wap.util.RequstUtil;
import com.financing.wap.util.StringUtil;
import com.financing.wap.vo.admin.AdminArticleInfoVO;
import com.financing.wap.web.controller.BaseController;

@Controller("adminDstArticleController")
@RequestMapping("/adminapi/dstArticle")
public class DstArticleController extends BaseController  { 

	private Logger logger = Logger.getLogger(getClass());

	@Autowired
	private IDstArticleService dstArticleService;
	
	@Autowired
	private IDstUserVisitLogService dstUserVisitLogService;
	
    @Autowired
    private WeixinService weixinJincsServiceImpl;
    
    @Autowired
    private ICommonService commonService;
    
    @Autowired
    private IDstUserArticleService dstUserAritcleService;

    @Autowired
    private IDstOperationLogService dstOperationLogService;
    
    @Autowired
    private IDstNewrankArticleService dstNewrankArticleService;

	
	@RequestMapping("/listDstArticle.shtml")
	@ResponseBody
	public ResultMap listDstArticle(HttpServletRequest request, AdminArticleInfoVO dstArticle, Pager pager){
		ResultMap result = new ResultMap();
		
		try{
			logger.info("query admin listDstArticle list begin .......");

			dstArticle.setBegin(pager.getStartIndex());
			dstArticle.setPageSize(pager.getPageSize());
			List<AdminArticleInfoVO> dstArticleList = null;
			int count = commonService.adminArticleInfoCount(dstArticle);
			pager.setTotalCount(count);
			if(count > 0){
				dstArticleList = commonService.adminAllArticleInfo(dstArticle);
			}else{
				dstArticleList = Collections.emptyList();
			}
			
			result.setAttribute("list",dstArticleList);
			
			result.setAttribute("pager", pager);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			
			logger.info("query dstArticle list end .......");
		}catch(Exception e){
			log.error("query dstArticle error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		
		return result;
	}
	public static void main(String[] args) {
		//批量处理
		String fecthAll = batchYoudao("https://mp.weixin.qq.com/s/EYj1Qn2Q7PKpFvHnDDbCcA");
		System.out.println(fecthAll);
	}
	/***
	 * 批量获取有道云收藏文章地址
	 * @param url
	 * @return
	 */
	private static String batchYoudao(String url) {
         if (url.matches("https?://.*?")&&url.contains("weixin.qq.com")) {
        	 String lists="";
        	 String doRequest = RequstUtil.doRequest(url);
        	 String content=doRequest.split("期.*?#")[1];
        	 String regex="<a href=\"(.*?)\" target=\"_blank\" data-linktype=\"2\"><strong style=\".*?\"><span style=\"text-decoration: underline;\">.*?</span></strong></a>";
        	 List<String> fecthAll = StringUtil.fecthAll(content, regex, 1);
        	 for (int i = 0; i < fecthAll.size(); i++) {
        		 lists+=","+fecthAll.get(i);
        	 }
        	 return lists;
         }
         return "";
	}
	
	@RequestMapping("/addDstArticle.shtml")
	@ResponseBody
	public ResultMap addDstArticle(HttpServletRequest request, DstArticleDTO dstArticle){
		ResultMap result = new ResultMap();
		
		try{
			logger.info("query addDstArticle  begin .......");


			String categories = request.getParameter("categories");
			String wxPath = request.getParameter("wxPath");
			String isYoudao = request.getParameter("isYoudao");
			String fetchId=request.getParameter("fetchId");
			
            //参数  默认
            if(StringUtil.isNullOrEmptyStr(categories,wxPath)){
                result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
                result.setStatus(ResultMap.STATUS.FAILE);
                return result;
            }
            
            //如果是有道收藏list
            if(StringUtils.isNotBlank(isYoudao)){
            	try {
					wxPath=batchYoudao(wxPath);
				} catch (Exception e) {
					logger.error("batchYoudao error:",e);
					result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
	                result.setStatus(ResultMap.STATUS.FAILE);
	                return result;
				}
            }
            
            String[] wxPaths = wxPath.split(",");
            //取其中一条的id  为一个的是有用
            String dstArticleCode = "";
            for(String url :wxPaths){
                String regex = "https?://.*?";
                if (url.matches(regex)) {
                    logger.info("拦截到地址:处理为可用文章..");
                    if (url.contains("mp.weixin.qq.com")||url.contains("work.weixin.qq.com")) {
                        Map<String,String> map = new HashMap<String, String>();
                        map.put("content",url);
                        map.put("userName","SFA运营");
                        map.put("articleStatus","0");//0：待上架，1 ：已上架
                        map.put("categories",categories);
                        map.put("resource","1");//文章来源1后台上传2用户所属
                        map.put("wxpathurl",url);
                        DstArticleDTO createArticle = commonService.createArticle(map);
                        dstArticleCode=createArticle.getDstArticleCode();
                    }
                }
            }
            //fetchid 抓取id 更新
            if(StringUtils.isNotBlank(fetchId)){
            	DstNewrankArticleDTO dstNewrankArticle=new DstNewrankArticleDTO();
            	dstNewrankArticle.setId(Integer.parseInt(fetchId));
            	dstNewrankArticle.setFlagFetch("2");
            	dstNewrankArticle.setUpdateBy("admin");
            	dstNewrankArticle.setUpdateDate(new Date());
            	dstNewrankArticle.setArticleCode(dstArticleCode);
            	dstNewrankArticleService.update(dstNewrankArticle);
            }
            
			result.setAttribute("dstArticleCode",dstArticleCode);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			
			logger.info("query detail dstArticle  end .......");
		}catch(Exception e){
			log.error("query detail dstArticle error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		
		return result;
	}
    @RequestMapping("/detailDstArticle.shtml")
    @ResponseBody
    public ResultMap detailDstArticle(HttpServletRequest request){
        ResultMap result = new ResultMap();

        try{
            logger.info("query addDstArticle  begin .......");

            String id=request.getParameter("id");
            String articleCode=request.getParameter("articleCode");
            String userOpenid=request.getParameter("userOpenId");
            DstArticleDTO article = null;
            if(StringUtils.isNotBlank(id)){
            	article =dstArticleService.loadById(Integer.parseInt(id));
            }else if(StringUtils.isNotBlank(articleCode)){
            	DstArticleDTO dstArticle=new DstArticleDTO();
            	dstArticle.setDstArticleCode(articleCode);
            	article =dstArticleService.queryListGetFirst(dstArticle);
            }
            //文章不存在
            if(article==null||article.getId()==null){
                result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
                result.setStatus(ResultMap.STATUS.FAILE);
                return result;
            }
            //如果传了 
            if(StringUtils.isNotBlank(userOpenid)){
            	DstUserArticleDTO dstUserArticle=new DstUserArticleDTO();
            	dstUserArticle.setUserOpenid(userOpenid);
            	dstUserArticle.setDstArticleCode(article.getDstArticleCode());
            	DstUserArticleDTO d = dstUserAritcleService.queryListGetFirst(dstUserArticle);
            	if(d.getId()==null){
            	    result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
                    result.setStatus(ResultMap.STATUS.FAILE);
                    return result;
            	}
            	article.setContent(d.getDstArticleContent());
            	article.setUserOpenId(userOpenid);
            	article.setDescription(d.getDescription());
            	article.setThumbnail(d.getThumbnail());
            	article.setTitle(d.getTitle());
            }
            result.setAttribute("dto",article);
            result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
            result.setStatus(ResultMap.STATUS.SUCCESS);

            logger.info("query detail dstArticle  end .......");
        }catch(Exception e){
            log.error("query detail dstArticle error!",e);
            result.setStatus(ResultMap.STATUS.ERROR);
            result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
        }

        return result;
    }
    /***
     * id   
     * articleStatus  文章状态
     * deleteTag   删除
     * @param request
     * @param dstArticle
     * @return
     */
    @RequestMapping("/updateDstArticleStatus.shtml")
	@ResponseBody
	public ResultMap updateDstArticleStatus(HttpServletRequest request, DstArticleDTO dstArticle){
		ResultMap result = new ResultMap();
		
		try{
			logger.info("updateDstArticleStatus  begin .......");

            Date now =  new Date();
            String remark = request.getParameter("remark");
            remark  =  StringUtils.isBlank(remark)?"":remark;

            String userOpenId = dstArticle.getUserOpenId();
            
        	if(StringUtils.isNotBlank(dstArticle.getDeleteTag())){
        		remark = "删除文章  "+  remark;
        	}else if(StringUtils.isNotBlank(dstArticle.getArticleStatus())){
        		remark = "修改文章  "+ (dstArticle.getArticleStatus().equals("1")?"上架":"下架");
        	}
        	
        	String operationBy = getSession(true).getAttribute("name") == null ?"admin.":getSession(true).getAttribute("name").toString();

        	if(StringUtils.isBlank(userOpenId)){
            	if(dstArticle.getId()==null){
                 	DstArticleDTO d=new DstArticleDTO();
                	d.setDeleteTag(CommonStatus.DELETE_TAG_NORMAL);
                	d.setDstArticleCode(dstArticle.getDstArticleCode());
                	DstArticleDTO re = dstArticleService.queryListGetFirst(d);
                	re.setDeleteTag(CommonStatus.DELETE_TAG_DELETE);
                	re.setUpdateDate(now);
                	re.setUpdateBy(operationBy);
                	dstArticleService.update(re);
            	}else{
            		dstArticle.setUpdateDate(now);
            		dstArticle.setUpdateBy(operationBy);
            		dstArticleService.update(dstArticle);
            	}
            }else{
            	DstUserArticleDTO d=new DstUserArticleDTO();
            	d.setDeleteTag(CommonStatus.DELETE_TAG_NORMAL);
            	d.setDstArticleCode(dstArticle.getDstArticleCode());
            	d.setUserOpenid(userOpenId);
            	DstUserArticleDTO re = dstUserAritcleService.queryListGetFirst(d);
            	re.setDeleteTag(CommonStatus.DELETE_TAG_DELETE);
            	re.setUpdateDate(now);
            	re.setUpdateBy(operationBy);
            	dstUserAritcleService.update(re);
            }

            //添加操作日志
            DstOperationLogDTO operationLogDTO = new DstOperationLogDTO();
			operationLogDTO.setOperationBy(operationBy);
            operationLogDTO.setUserOpenid(userOpenId);
            operationLogDTO.setOperationCode(dstArticle.getDstArticleCode());
            operationLogDTO.setOperationDesc(remark);
            operationLogDTO.setCreateBy(operationLogDTO.getOperationBy());
            operationLogDTO.setUpdateBy(operationLogDTO.getOperationBy());
            operationLogDTO.setCreateDate(now);
            operationLogDTO.setUpdateDate(now);
            dstOperationLogService.insert(operationLogDTO);

			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			
			logger.info("updateDstArticleStatus  end .......");
		}catch(Exception e){
			log.error("updateDstArticleStatus error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		
		return result;
	}
    /***
     * ids 推荐文章ids
     *
     * @param request
     * @param dstArticle
     * @return
     */
    @RequestMapping(value="/articleRecomment.shtml")
    @ResponseBody
    public ResultMap articleRecomment(HttpServletRequest request, DstArticleDTO dstArticle){
        ResultMap result = new ResultMap();

        try{
            logger.info("articleRecomment  begin .......");

            Date now =  new Date();
            String ids = request.getParameter("ids");

            if(StringUtils.isBlank(ids) || StringUtils.isBlank(dstArticle.getArcticleRecomment())){
                result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
                result.setStatus(ResultMap.STATUS.FAILE);
                return result;
            }

            // 判断选择的文章是否存在推荐过的-有的话返回错误
            for(String id :ids.split(",")){
                DstArticleDTO articleDTO =dstArticleService.loadById(Integer.valueOf(id));
                if(articleDTO != null && StringUtils.isNotBlank(articleDTO.getPublishedDate())){
                    result.setStatusCode(ResultMap.STATUS_CODE_OPERATE_ERROE);
                    result.setMessage("选择的文章已经存在推荐!");
                    result.setStatus(ResultMap.STATUS.SUCCESS);
                    return result;
                }
            }

            //判断-每天只能推荐5篇
            DstArticleDTO dstArticleCount = new DstArticleDTO();
            dstArticleCount.setPublishedDate(StringUtils.isNotBlank(dstArticle.getPublishedDate())?dstArticle.getPublishedDate():DateUtil.getDate("yyyy-MM-dd"));
            dstArticleCount.setDeleteTag(CommonStatus.DELETE_TAG_NORMAL);
            dstArticleCount.setArticleStatus("1");
            dstArticleCount.setArcticleRecomment(dstArticle.getArcticleRecomment());
            int count = dstArticleService.queryListCount(dstArticleCount);
            String[]  idsStr = ids.split(",");
            
            if(!"0".equals(dstArticle.getArcticleRecomment()) && count+idsStr.length >5){
                result.setStatusCode(ResultMap.STATUS_CODE_OPERATE_ERROE);
                result.setMessage("每天只能推荐5篇! 今日已经推荐:"+count);
                result.setStatus(ResultMap.STATUS.SUCCESS);
                return result;
            }

            //实时发送 -判断逻辑
            if("0".equals(dstArticle.getArcticleRecomment()) && count+idsStr.length >3){
                result.setStatusCode(ResultMap.STATUS_CODE_OPERATE_ERROE);
                result.setMessage("每天只能实时推荐3篇! 今日已经推荐:"+count);
                result.setStatus(ResultMap.STATUS.SUCCESS);
                return result;
            }
            //实时推荐
            if("0".equals(dstArticle.getArcticleRecomment())){
            	dstArticle.setPublishedDate(DateUtil.getDate("yyyy-MM-dd"));
            }
            
            for(String id :ids.split(",")){
            	
                dstArticle.setId(Integer.valueOf(id));
                dstArticleService.update(dstArticle);

                //添加操作日志
                DstOperationLogDTO operationLogDTO = new DstOperationLogDTO();
                operationLogDTO.setOperationBy(getSession(true).getAttribute("name") == null ?"admin.":getSession(true).getAttribute("name").toString());
                operationLogDTO.setOperationCode(dstArticle.getId().toString());
                operationLogDTO.setOperationDesc("修改文章  推荐"+("0".equals(dstArticle.getArcticleRecomment())?"实时":"定时"));
                operationLogDTO.setCreateBy(operationLogDTO.getOperationBy());
                operationLogDTO.setUpdateBy(operationLogDTO.getOperationBy());
                operationLogDTO.setCreateDate(now);
                operationLogDTO.setUpdateDate(now);
                dstOperationLogService.insert(operationLogDTO);
            }

            //实时发送
            if("0".equals(dstArticle.getArcticleRecomment())){
                Map<String,String> map = new HashMap<String,String>();
                map.put("id",ids);
                map.put("recommentTarget",dstArticle.getRecommentTarget());
                commonService.articleRealTimePush(map);
            }


            result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
            result.setStatus(ResultMap.STATUS.SUCCESS);

            logger.info("updateDstArticle  end .......");
        }catch(Exception e){
            log.error("updateDstArticle error!",e);
            result.setStatus(ResultMap.STATUS.ERROR);
            result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
        }

        return result;
    }


    /***
     * id
     * @param request
     * @param dstArticle
     * @return
     */
    @RequestMapping(value="/updateDstArticle.shtml",method=RequestMethod.POST)
    @ResponseBody
    public ResultMap updateDstArticle(HttpServletRequest request, DstArticleDTO dstArticle){
        ResultMap result = new ResultMap();

        try{
            logger.info("updateDstArticle  begin .......");
            Date now =  new Date();
            String operationBy = getSession(true).getAttribute("name") == null ?"admin.":getSession(true).getAttribute("name").toString();
            String remark = request.getParameter("remark");

            remark  =  StringUtils.isBlank(remark)?"":remark;
            if(dstArticle.getId()==null){
                result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
                result.setStatus(ResultMap.STATUS.FAILE);
                return result;
            }
           /* if(StringUtils.isNotBlank(dstArticle.getPublishedDate())){
                dstArticle.setArcticleRecomment("1");
            }else{
                dstArticle.setArcticleRecomment("2");
            }*/
            dstArticle.setUpdateBy(operationBy);
            dstArticle.setUpdateDate(now);
            dstArticleService.update(dstArticle);

            //添加操作日志
            DstOperationLogDTO operationLogDTO = new DstOperationLogDTO();
			operationLogDTO.setOperationBy(operationBy);
            operationLogDTO.setOperationCode(dstArticle.getDstArticleCode());
            operationLogDTO.setOperationDesc("修改文章  "+remark);
            operationLogDTO.setCreateBy(operationLogDTO.getOperationBy());
            operationLogDTO.setUpdateBy(operationLogDTO.getOperationBy());
            operationLogDTO.setCreateDate(now);
            operationLogDTO.setUpdateDate(now);
            dstOperationLogService.insert(operationLogDTO);

            result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
            result.setStatus(ResultMap.STATUS.SUCCESS);

            logger.info("updateDstArticle  end .......");
        }catch(Exception e){
            log.error("updateDstArticle error!",e);
            result.setStatus(ResultMap.STATUS.ERROR);
            result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
        }

        return result;
    }


    @RequestMapping("/listDstArticleOperation.shtml")
    @ResponseBody
    public ResultMap listDstArticleOperation(HttpServletRequest request, DstOperationLogDTO dstOperationLog){
        ResultMap result = new ResultMap();

        try{
            logger.info("query listDstArticleOperation list begin .......");

            List<DstOperationLogDTO>    dstArticleList = dstOperationLogService.queryList(dstOperationLog);

            result.setAttribute("list",dstArticleList);
            result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
            result.setStatus(ResultMap.STATUS.SUCCESS);

            logger.info("query dstArticle list end .......");
        }catch(Exception e){
            log.error("query dstArticle error!",e);
            result.setStatus(ResultMap.STATUS.ERROR);
            result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
        }

        return result;
    }
}
